import { msgTip } from "./MsgTipApi";

class WebSocketManager{
  defaultBaseUrl = 'ws://127.0.0.1:8000/websocket/chat/'
  constructor(){
    this.socket = null;
    this.isConnect = false;
  }

  connect(url){
    let _this = this;
    wx.connectSocket({
      url: _this.defaultBaseUrl + url,
      success(){
        console.log('建立连接成功');
      },
      fail(){
        console.log('建立连接失败');
      }
    });
    wx.onSocketOpen((result) => {
      console.log('连接已经建立');
      _this.isConnect = true
    });
    wx.onSocketMessage((result) => {
      console.log('收到服务器的消息：',result);
      // 需要在这里进行消息监听处理
    });
    wx.onSocketError(result =>{
      console.log('连接失败');
      _this.isConnect = false
    });
  }

  sendMsg(msg){
    if(this.isConnect){
      wx.sendSocketMessage({
        data: msg,
      })
    }else{
      msgTip({title:'创立连接失败，无法发送消息'})
    }
  }
}
export const websocket = new WebSocketManager();
